package com.imooc.service;

import com.imooc.es.pojo.Items;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;

import java.util.ArrayList;
import java.util.List;


@Slf4j
public class MySearchResult implements SearchResultMapper {

    private static final String FILE_NAME = "itemName";

    @Override
    public <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> aClass, Pageable pageable) {

        List<Items> listHigh = new ArrayList<>();
        for (SearchHit hit : response.getHits()) {
            HighlightField highlightField = hit.getHighlightFields().get(FILE_NAME);
            String itemName = highlightField.getFragments()[0].toString();

            String itemId = (String) hit.getSourceAsMap().get("itemId");
            String imgUrl = (String) hit.getSourceAsMap().get("imgUrl");
            Integer price = (Integer) hit.getSourceAsMap().get("price");
            Integer sellCounts = (Integer) hit.getSourceAsMap().get("sellCounts");

            Items items = new Items();
            items.setItemId(itemId);
            items.setItemName(itemName);
            items.setPrice(price);
            items.setImgUrl(imgUrl);
            items.setSellCounts(sellCounts);

            listHigh.add(items);
        }

        return new AggregatedPageImpl<>((List<T>) listHigh, pageable, response.getHits().totalHits);
    }

    @Override
    public <T> T mapSearchHit(SearchHit searchHit, Class<T> aClass) {
        return null;
    }


}
